package com.panda.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.panda.common.core.domain.AjaxResult;
import com.panda.common.core.domain.entity.SysDept;
import com.panda.common.utils.DateUtils;
import com.panda.common.utils.StringUtils;
import com.panda.system.common.constant.EnumConstants;
import com.panda.system.domain.PandaStore;
import com.panda.system.domain.PandaTask;
import com.panda.system.domain.TPandaTask;
import com.panda.system.dto.DistributionTaskDto;
import com.panda.system.mapper.TPandaTaskMapper;
import com.panda.system.service.IPandaStoreService;
import com.panda.system.service.IPandaTaskService;
import com.panda.system.service.ISysDeptService;
import com.panda.system.service.ITPandaTaskService;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 任务信息总Service业务层处理
 * 
 * @author panda
 * @date 2021-02-08
 */
@Service
@Transactional
public class TPandaTaskServiceImpl implements ITPandaTaskService 
{
    private static final Logger log = LoggerFactory.getLogger(ITPandaTaskService.class);
    @Autowired
    private TPandaTaskMapper tPandaTaskMapper;

    @Autowired
    private IPandaTaskService pandaTaskService;
    @Autowired
    private IPandaStoreService iPandaStoreService;

    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询任务信息总
     * 
     * @param taskId 任务信息总ID
     * @return 任务信息总
     */
    @Override
    public TPandaTask selectTPandaTaskById(Long taskId)
    {
        return tPandaTaskMapper.selectTPandaTaskById(taskId);
    }

    /**
     * 查询任务信息总列表
     * 
     * @param tPandaTask 任务信息总
     * @return 任务信息总
     */
    @Override
    public List<TPandaTask> selectTPandaTaskList(TPandaTask tPandaTask)
    {
        return tPandaTaskMapper.selectTPandaTaskList(tPandaTask);
    }

    /**
     * 新增任务信息总
     * 
     * @param tPandaTask 任务信息总
     * @return 结果
     */
    @Override
    public AjaxResult insertTPandaTask(TPandaTask tPandaTask)
    {
        tPandaTask.setCreateTime(DateUtils.getNowDate());
        List<PandaStore> pandaStores = iPandaStoreService.selectPandaStoreListByNames(Arrays.asList(tPandaTask.getStoreName()));
        if(pandaStores.size()==0){
            return AjaxResult.error("未查询到店铺信息，请先新增店铺！");

        }
        tPandaTask.setStoreId(pandaStores.get(0).getStoreId());
        // 设置初始值
        tPandaTaskMapper.insertTPandaTask(tPandaTask);
        return AjaxResult.success();
    }

    /**
     * 修改任务信息总
     * 
     * @param tPandaTask 任务信息总
     * @return 结果
     */
    @Override
    public int updateTPandaTask(TPandaTask tPandaTask)
    {
        tPandaTask.setUpdateTime(DateUtils.getNowDate());
        // 更新部门任务明细
        PandaTask pandaTask = new PandaTask();
        pandaTask.setParentTaskId(tPandaTask.getTaskId());
        List<PandaTask> pandaTasks = pandaTaskService.selectPandaTaskList(pandaTask);
        for(PandaTask task:pandaTasks){
            processDeptTaskList(task,tPandaTask);
            pandaTaskService.updatePandaTask(task);
        }
        return tPandaTaskMapper.updateTPandaTask(tPandaTask);
    }

    /**
     * 批量删除任务信息总
     * 
     * @param taskIds 需要删除的任务信息总ID
     * @return 结果
     */
    @Override
    public AjaxResult deleteTPandaTaskByIds(Long[] taskIds)
    {
        // 查询是否存在关联的部门任务信息
        for(Long id:taskIds){
            PandaTask pandaTask =new PandaTask();
            pandaTask.setParentTaskId(id);
            List<PandaTask> pandaTasks = pandaTaskService.selectPandaTaskList(pandaTask);
            if(!CollectionUtils.isEmpty(pandaTasks)){
                return AjaxResult.error("删除任务失败！任务id："+id+",存在关联的部门任务！");
            }
        }
        tPandaTaskMapper.deleteTPandaTaskByIds(taskIds);

        return AjaxResult.success("删除任务成功！");
    }

    /**
     * 删除任务信息总信息
     * 
     * @param taskId 任务信息总ID
     * @return 结果
     */
    @Override
    public int deleteTPandaTaskById(Long taskId)
    {
        return tPandaTaskMapper.deleteTPandaTaskById(taskId);
    }

    @Override
    public AjaxResult importTask(TPandaTask task) {
        if(task == null){
            return AjaxResult.error("导入任务列表为空！");
        }
        if(Strings.isEmpty(task.getStoreName())){
            // 店铺为空
            return AjaxResult.error("导入任务失败，店铺为空！");
        }

        if(Strings.isEmpty(task.getResponsibleSet())){
            return AjaxResult.error("导入任务失败，负责组为空！");
        }
        if(CollectionUtils.isEmpty(task.getDeptTasks())){
            return AjaxResult.error("导入任务失败，任务明细为空！");
        }
        log.info("importTask :{}",JSON.toJSONString(task));
        // 部门信息
        SysDept sysDept = sysDeptService.selectDeptByName(task.getResponsibleSet());
        task.setResponsibleSet(String.valueOf(sysDept.getDeptId()));
        if(Strings.isNotEmpty(task.getOriginalSet())){
            SysDept sysOriginaDept = sysDeptService.selectDeptByName(task.getOriginalSet());
            task.setOriginalSet(String.valueOf(sysOriginaDept.getDeptId()));
        }

        // 获取任务对应的店铺信息
        List<String> storeNames = Collections.singletonList(task.getStoreName());
        Set<String> nameSet = new HashSet<>(storeNames);
        List<PandaStore> pandaStores = iPandaStoreService.selectPandaStoreListByNames(storeNames);
        if(CollectionUtils.isEmpty(pandaStores)){
            return AjaxResult.error("店铺信息不存在，请维护！");
        }
        if(!CollectionUtils.isEmpty(pandaStores)){
            List<String> names = pandaStores.stream().map(PandaStore::getStoreName).collect(Collectors.toList());
            // 去重
            nameSet.removeIf(item->names.contains(item));
        }
        // 新增店铺
        nameSet.forEach(item->{
            item.trim();
            PandaStore store = new PandaStore(item);
            int id = iPandaStoreService.insertPandaStore(store);
            store.setStoreId(Long.valueOf(id));
            pandaStores.add(store);
        });
        Map<String,PandaStore> storeMap = new HashMap<>();
        pandaStores.forEach(item->storeMap.put(item.getStoreName(),item));

        PandaStore store = storeMap.get(task.getStoreName());
        task.setStoreId(store.getStoreId());
        // 分配时间
        task.setTastDate(new Date());
        // 任务名称
        task.setTaskName("【"+task.getStoreName()+"】"+task.getProductName());
        // 添加部门任务列表
        List<PandaTask> deptTasks = new ArrayList<>();
        if(task.getAdjustTaskId()!= null&&Strings.isNotEmpty(Long.toString(task.getAdjustTaskId()))&&task.getAdjustTaskId()!=0){
            // 更新任务
            TPandaTask tPandaTask = tPandaTaskMapper.selectTPandaTaskById(task.getAdjustTaskId());
            PandaTask pandaTask = new PandaTask();
            pandaTask.setParentTaskId(tPandaTask.getTaskId());
            List<PandaTask> pandaTasks = pandaTaskService.selectPandaTaskList(pandaTask);
            List<PandaTask> deptImportTasks = task.getDeptTasks();
            Map<String,PandaTask> deptImportTaskMap = new HashMap<>();
            deptImportTasks = deptImportTasks.stream().filter(item->item.getTastDate()!=null).collect(Collectors.toList());
            if(CollectionUtils.isEmpty(deptImportTasks)){
                return AjaxResult.error("导入任务失败，任务明细为空！");
            }
            deptImportTasks.forEach(item->deptImportTaskMap.put(dateToString(item.getTastDate()),item));
            List<PandaTask> failureTask = new ArrayList<>();
            List<String> dateStrList = new ArrayList<>();
            // 获取需要调整的任务
            for(PandaTask deptTask:pandaTasks){
                dateStrList.add(dateToString(deptTask.getTastDate()));
                PandaTask taskItem = deptImportTaskMap.get(dateToString(deptTask.getTastDate()));
                if(taskItem!=null&&taskItem.getTastDate().after(new Date())){
                    failureTask.add(deptTask);
                    deptTasks.add(taskItem);
                }
            }
            for(PandaTask deptImportTask:deptImportTasks){
                if(CollectionUtils.isEmpty(dateStrList)){
                    deptTasks.add(deptImportTask);
                    continue;
                }
                String dateStr = dateToString(deptImportTask.getTastDate());
                if(!dateStrList.contains(dateStr)){
                    deptTasks.add(deptImportTask);
                }
            }

            // 需新增的任务

            pandaTaskService.failureTask(failureTask);
            task.setTaskId(tPandaTask.getTaskId());
            tPandaTaskMapper.updateTPandaTask(task);
        }else {
            deptTasks= task.getDeptTasks();
            tPandaTaskMapper.insertTPandaTask(task);
        }

        for(PandaTask deptTask:deptTasks){
            if(deptTask.getTastDate()==null){
                continue;
            }
            processDeptTaskList(deptTask,task);
            deptTask.setStatus(EnumConstants.TaskType.NEW_CREATE.getCode());
            pandaTaskService.insertPandaTask(deptTask);
        }
        // 自动分配
        DistributionTaskDto dto = new DistributionTaskDto();
        dto.setDeptId(task.getResponsibleSet());
        List<Long> ids = deptTasks.stream().map(PandaTask::getTaskId).collect(Collectors.toList());
        dto.setTaskIds(ids);
        pandaTaskService.distributionTask(dto);


        return AjaxResult.success("导入任务列表完成！任务Id："+task.getTaskId());
    }

    private String dateToString(Date date){
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        return sdf.format(date);
    }

    private void processDeptTaskList(PandaTask deptTask,TPandaTask task){
        deptTask.setParentTaskId(task.getTaskId());
        deptTask.setResponsibleUserId(task.getResponsibleSet());
        deptTask.setKeywords(task.getKeywords());
        deptTask.setStoreId(task.getStoreId());
        deptTask.setStoreName(task.getStoreName());
        deptTask.setPicture(task.getPicture());
        deptTask.setPrice(task.getPrice());
        deptTask.setProductName(task.getProductName());
        deptTask.setUrl(task.getUrl());
        // 比例计算，百分比
        if(!StringUtils.isEmpty(task.getEvaluation())){
            try{
                DecimalFormat df = new DecimalFormat("0.00%");
                Double aDouble = Double.valueOf(task.getEvaluation());
                deptTask.setEvaluation(df.format(aDouble));
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        deptTask.setTaskName("【"+task.getStoreName()+"】"+task.getProductName());
    }
}
